package servlet;

import exception.UnsupportedTypeException;
import pojo.entity.User;
import util.SimpleBeanConvertor;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;

@WebServlet(name = "TestServlet", urlPatterns = "/test")
public class TestServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求和响应的字符编码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        // 调用doGet方法处理请求
        this.doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        try {
            // 使用SimpleBeanConvertor将请求参数转换为User对象
            User user = SimpleBeanConvertor.convert(request, User.class);
            // 输出User对象信息到控制台
            System.out.println("User object created: " + user);

            // 如果需要，可以将User对象存储到请求属性中，或者进行其他处理
            request.setAttribute("user", user);

            // 跳转到一个JSP页面或其他Servlet
            request.getRequestDispatcher("/result.jsp").forward(request, response);

        } catch (UnsupportedTypeException e) {
            // 捕获并处理UnsupportedTypeException异常
            response.getWriter().println("Error: Unsupported type encountered.");
            e.printStackTrace();
        } catch (ParseException e) {
            // 捕获并处理ParseException异常
            response.getWriter().println("Error: Date format error.");
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // 捕获并处理InvocationTargetException异常
            response.getWriter().println("Error: Invocation target error.");
            e.printStackTrace();
        } catch (InstantiationException e) {
            // 捕获并处理InstantiationException异常
            response.getWriter().println("Error: Instantiation error.");
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // 捕获并处理IllegalAccessException异常
            response.getWriter().println("Error: Illegal access error.");
            e.printStackTrace();
        } catch (Exception e) {
            // 捕获其他未知异常
            response.getWriter().println("Error: An unexpected error occurred.");
            e.printStackTrace();
        }
    }
}